﻿
using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
namespace DZParallelLib.Utility
{
    static class AsyncHelpers
    {
        /// <summary>
        /// Load an image from a file using async read.
        /// </summary>
        /// <param name="f">File we are going to load</param>
        /// <param name="actOnImage">The function to use. We have to do this because the input stream and data must remain allocated during use. Do not cache the image!</param>
        /// <returns></returns>
        public async static Task LoadImage(this FileInfo f, Action<Image> actOnImage)
        {
            using (var reader = f.OpenRead())
            {
                byte[] data = new byte[f.Length];
                await reader.ReadAsync(data, 0, data.Length);
                reader.Close();
                using (var mr = new MemoryStream(data))
                {
                    using (var i = Image.FromStream(mr))
                    {
                        actOnImage(i);
                    }
                }
            }
        }
    }
}
